package com.bw.zuul.filter;

import com.alibaba.fastjson.JSON;
import com.bw.common.vo.ResultVO;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author qpxbo
 */
@Component
public class MyFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {

        //判断请求参数是否携带token，没有token 则提示 没有权限
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String token = request.getParameter("token");
        if (StringUtils.isEmpty(token)){
            currentContext.setResponseStatusCode(401);
            currentContext.setSendZuulResponse(false);
            HttpServletResponse response = currentContext.getResponse();
            response.setContentType("application/json;charset=utf-8");
            try {
                PrintWriter writer = response.getWriter();
                writer.write(JSON.toJSONString(ResultVO.fail("500","token 不允许为空",null)));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
